package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.QuotationMapper;
import com.intelligent.pojo.CustomerManagement;
import com.intelligent.pojo.Quotation;
import com.intelligent.pojo.QuotationDetail;
import com.intelligent.pojo.TUser;
import com.intelligent.service.CustomerManagementService;
import com.intelligent.service.QuotationDetailService;
import com.intelligent.service.QuotationService;
import com.intelligent.service.TUserService;
import com.intelligent.vo.QuotationPageReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//报价单
@Service
public class QuotationServiceImpl extends ServiceImpl<QuotationMapper, Quotation>
        implements QuotationService {

    @Autowired
    private CustomerManagementService customerManagementService;

    @Autowired
    private TUserService tUserService;

    @Autowired
    private QuotationDetailService quotationDetailService;

    @Override
    public Page<Quotation> pageWithRelations(QuotationPageReq quotationPageReq) {
        Page<Quotation> page = new Page<>(quotationPageReq.getPageNum(), quotationPageReq.getPageSize());
        LambdaQueryWrapper<Quotation> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        if (quotationPageReq.getQuotationNo() != null && !quotationPageReq.getQuotationNo().isEmpty()) {
            wrapper.like(Quotation::getQuotationNo, quotationPageReq.getQuotationNo());
        }

        wrapper.orderByDesc(Quotation::getQuotationId);
        Page<Quotation> result = this.page(page, wrapper);

        // 关联客户表获取客户名称
        fillCustomerNames(result);

        // 关联用户表获取用户的姓名
        fillSalesPersonNames(result);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Quotation createQuotation(Quotation quotation) {
        // 设置默认状态
        if (quotation.getStatus() == null) {
            quotation.setStatus(1); // 报价中
        }
        if (quotation.getApprovalStatus() == null) {
            quotation.setApprovalStatus(1); // 待审批
        }
        // 为避免 DB 对 quotation_no 的非空/唯一约束，先写入一个临时编号
        String tempNo = "TMP-" + System.currentTimeMillis();
        quotation.setQuotationNo(tempNo);

        // 首次保存以获取自增ID
        boolean saved = this.save(quotation);
        if (!saved) {
            throw new RuntimeException("保存报价单失败");
        }

        // 生成报价单号：BJ+年份+月份+4位数自增ID
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String idPart = String.format("%04d", quotation.getQuotationId());
        String quotationNo = "BJ" + yearMonth + idPart;
        quotation.setQuotationNo(quotationNo);

        // 更新记录写入报价单号
        boolean updated = this.updateById(quotation);
        if (!updated) {
            throw new RuntimeException("写入报价单号失败");
        }
        // 创建成功后，自动基于报价单ID生成一条默认报价明细
        boolean detailOk = quotationDetailService.generateDefaultDetailForQuotation(quotation.getQuotationId());
        if (!detailOk) {
            throw new RuntimeException("自动生成报价明细失败");
        }

        return quotation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Quotation createQuotationWithDetails(Quotation quotation, List<QuotationDetail> quotationDetails) {
        // 先创建报价单
        Quotation createdQuotation = createQuotation(quotation);

        // 如果有明细，则创建明细；否则生成一条默认明细
        if (quotationDetails != null && !quotationDetails.isEmpty()) {
            // 设置报价单ID
            for (QuotationDetail detail : quotationDetails) {
                detail.setQuotationId(createdQuotation.getQuotationId());
            }

            // 批量创建明细
            boolean detailSaved = quotationDetailService.batchCreateQuotationDetails(quotationDetails);
            if (!detailSaved) {
                throw new RuntimeException("创建报价明细失败");
            }
        } else {
            boolean ok = quotationDetailService.generateDefaultDetailForQuotation(createdQuotation.getQuotationId());
            if (!ok) {
                throw new RuntimeException("自动生成默认报价明细失败");
            }
        }

        return createdQuotation;
    }

    @Override
    public Quotation getQuotationDetail(Long id) {
        Quotation quotation = this.getById(id);
        if (quotation == null) {
            return null;
        }

        // 关联客户表获取客户名称
        if (quotation.getCustomerId() != null) {
            CustomerManagement customer = customerManagementService.getById(quotation.getCustomerId());
            if (customer != null) {
                quotation.setCustomerName(customer.getCustomerName());
            }
        }

        // 关联用户表获取销售姓名
        if (quotation.getUId() != null) {
            TUser user = tUserService.getById(quotation.getUId());
            if (user != null) {
                quotation.setSalesPersonName(user.getRealName());
            }
        }

        return quotation;
    }


    private void fillCustomerNames(Page<Quotation> result) {
        if (result.getRecords() == null || result.getRecords().isEmpty()) {
            return;
        }

        List<Long> customerIds = result.getRecords().stream()
            .map(Quotation::getCustomerId)
            .filter(customerId -> customerId != null)
            .distinct()
            .collect(Collectors.toList());

        if (!customerIds.isEmpty()) {
            LambdaQueryWrapper<CustomerManagement> customerWrapper = new LambdaQueryWrapper<>();
            customerWrapper.in(CustomerManagement::getId, customerIds);
            List<CustomerManagement> customers = customerManagementService.list(customerWrapper);
            Map<Long, String> customerMap = customers.stream()
                .collect(Collectors.toMap(CustomerManagement::getId, CustomerManagement::getCustomerName));

            result.getRecords().forEach(quotation -> {
                if (quotation.getCustomerId() != null) {
                    quotation.setCustomerName(customerMap.get(quotation.getCustomerId()));
                }
            });
        }
    }


    private void fillSalesPersonNames(Page<Quotation> result) {
        if (result.getRecords() == null || result.getRecords().isEmpty()) {
            return;
        }

        List<Long> userIds = result.getRecords().stream()
            .map(Quotation::getUId)
            .filter(uId -> uId != null)
            .distinct()
            .collect(Collectors.toList());

        if (!userIds.isEmpty()) {
            LambdaQueryWrapper<TUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.in(TUser::getUserId, userIds);
            List<TUser> users = tUserService.list(userWrapper);
            Map<Long, String> userMap = users.stream()
                .collect(Collectors.toMap(TUser::getUserId, TUser::getRealName));

            result.getRecords().forEach(quotation -> {
                if (quotation.getUId() != null) {
                    quotation.setSalesPersonName(userMap.get(quotation.getUId()));
                }
            });
        }
    }
}
